import SwiftUI

struct LoginView: View {
    @Environment(\.presentationMode) var presentationMode
    @StateObject private var viewModel = LoginViewModel()
    @State private var phone = ""
    @State private var password = ""
    @State private var captcha = ""
    @State private var isPasswordLogin = true
    @State private var isAgree = false
    @State private var showingUserAgreement = false
    @State private var showingPrivacyPolicy = false
    
    var body: some View {
        ZStack {
            Color.white.edgesIgnoringSafeArea(.all)
            
            VStack(spacing: 20) {
                // 顶部关闭按钮
                HStack {
                    Spacer()
                    Button(action: {
                        presentationMode.wrappedValue.dismiss()
                    }) {
                        Image(systemName: "xmark")
                            .foregroundColor(.gray)
                            .padding()
                    }
                }
                
                // Logo
                Image("logo")
                    .resizable()
                    .scaledToFit()
                    .frame(width: 120, height: 120)
                    .padding(.top, 20)
                
                // 登录方式标题
                Text(isPasswordLogin ? "密码登录" : "验证码登录")
                    .font(.headline)
                    .fontWeight(.bold)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding(.horizontal)
                
                // 表单
                VStack(spacing: 15) {
                    // 手机号输入
                    HStack {
                        Image(systemName: "phone.fill")
                            .foregroundColor(.gray)
                        TextField("输入手机号码", text: $phone)
                            .keyboardType(.numberPad)
                    }
                    .padding()
                    .background(Color.gray.opacity(0.1))
                    .cornerRadius(8)
                    
                    if isPasswordLogin {
                        // 密码输入
                        HStack {
                            Image(systemName: "lock.fill")
                                .foregroundColor(.gray)
                            SecureField("填写登录密码", text: $password)
                        }
                        .padding()
                        .background(Color.gray.opacity(0.1))
                        .cornerRadius(8)
                    } else {
                        // 验证码输入
                        HStack {
                            Image(systemName: "message.fill")
                                .foregroundColor(.gray)
                            TextField("填写验证码", text: $captcha)
                                .keyboardType(.numberPad)
                            
                            Button(action: {
                                Task {
                                    await viewModel.sendSmsCode(phone: phone)
                                }
                            }) {
                                Text(viewModel.codeButtonText)
                                    .foregroundColor(viewModel.isCodeButtonEnabled ? .blue : .gray)
                            }
                            .disabled(!viewModel.isCodeButtonEnabled)
                        }
                        .padding()
                        .background(Color.gray.opacity(0.1))
                        .cornerRadius(8)
                    }
                }
                .padding(.horizontal)
                
                // 用户协议
                HStack {
                    Button(action: {
                        isAgree.toggle()
                    }) {
                        Image(systemName: isAgree ? "checkmark.square.fill" : "square")
                            .foregroundColor(isAgree ? ThemeHelper.shared.getColor() : .gray)
                    }
                    
                    Text("我已阅读并同意")
                        .font(.footnote)
                    
                    Button(action: {
                        showingUserAgreement = true
                    }) {
                        Text("《用户协议》")
                            .font(.footnote)
                            .foregroundColor(ThemeHelper.shared.getColor())
                    }
                    
                    Button(action: {
                        showingPrivacyPolicy = true
                    }) {
                        Text("《隐私政策》")
                            .font(.footnote)
                            .foregroundColor(ThemeHelper.shared.getColor())
                    }
                }
                .padding(.horizontal)
                
                // 登录按钮
                Button(action: {
                    Task {
                        if isPasswordLogin {
                            await viewModel.login(phone: phone, password: password)
                        } else {
                            await viewModel.loginWithSmsCode(phone: phone, code: captcha)
                        }
                    }
                }) {
                    Text("登录")
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 12)
                        .background(isAgree ? ThemeHelper.shared.getColor() : Color.gray)
                        .cornerRadius(25)
                }
                .disabled(!isAgree)
                .padding(.horizontal)
                
                // 切换登录方式按钮
                Button(action: {
                    isPasswordLogin.toggle()
                }) {
                    Text(isPasswordLogin ? "验证码登录" : "密码登录")
                        .foregroundColor(ThemeHelper.shared.getColor())
                        .font(.system(size: 14))
                }
                
                Spacer()
            }
            .padding()
            
            if viewModel.isLoading {
                Color.black.opacity(0.3).edgesIgnoringSafeArea(.all)
                ProgressView()
                    .progressViewStyle(CircularProgressViewStyle(tint: .white))
                    .scaleEffect(1.5)
            }
        }
        .alert(isPresented: $viewModel.showAlert) {
            Alert(title: Text("提示"), message: Text(viewModel.alertMessage), dismissButton: .default(Text("确定")))
        }
        .sheet(isPresented: $showingUserAgreement) {
            WebView(url: URL(string: "\(APIConfig.baseURL)/agreement/userinfo")!)
        }
        .sheet(isPresented: $showingPrivacyPolicy) {
            WebView(url: URL(string: "\(APIConfig.baseURL)/agreement/userprivacyinfo")!)
        }
        .onChange(of: viewModel.isLoggedIn) { isLoggedIn in
            if isLoggedIn {
                presentationMode.wrappedValue.dismiss()
            }
        }
    }
}

struct LoginViewPreview: PreviewProvider {
    static var previews: some View {
        LoginView()
    }
}